# -*- coding: utf-8 -*-
# 解析XML SAX 和 DOM

# DOM会把整个XML读入内存，解析慢，占用内存高，有点可以任意遍历树的节点
# SAX 是流模式，边读边解析，占用内存小，解析快
# 正常情况优先考虑SAX，因为DOM实在太占内存

from xml.parsers.expat import ParserCreate

class DefaultSaxHandler(object):
	def start_element(self,name,attrs):
		print('sax:start_element: %s, attrs: %s' % (name,str(attrs)))

	def end_element(self,name):
		print('sax:end_element: %s' % name)

	def char_data(self,text):
		print('sax:char_data: %s' % text)

xml = r'''<?xml version="1.0"?><ol>
    <li><a href="/python">Python</a></li>
    <li><a href="/ruby">Ruby</a></li>
</ol>'''

handler = DefaultSaxHandler()
parser = ParserCreate()
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(xml)